import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { Observable } from 'rxjs';
import { Reflector } from '@nestjs/core';
import type { Request } from 'express';
@Injectable()
export class RoleGuard implements CanActivate {
  constructor(private readonly reflector: Reflector) {}
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    this.reflector.get('roles', context.getHandler()); //第一个是key,要与controller中的setMetadata的key一致 ,第二个是context.getHandler()获取的数据
    const roles = this.reflector.get<string[]>('roles', context.getHandler());
    const res = context.switchToHttp().getRequest<Request>();
    console.log('role.guard.ts', roles);
    if (roles.includes(res.query.role as string)) {
      //判断是否包含该角色
      return true;
    }
    return false;
  }
}
